import {ApplicationRef, ComponentFactoryResolver, Injectable, Injector} from '@angular/core';
import {DhlWindowComponent} from '../../shared/components/dhlcomponent/window/dhl-window.component';
import {appInjector} from '../../shared/utils/app-injector';
import {DhlDrawerComponent} from '../../shared/components/dhlcomponent/drawer/dhl-drawer.component';
import {NzModalService} from "ng-zorro-antd/modal";
import {NzDrawerService} from "ng-zorro-antd/drawer";

@Injectable()
export class WindowService {

  constructor(private injector: Injector,
              private applicationRef: ApplicationRef,
              private modal: NzModalService,
              private componentFactoryResolver: ComponentFactoryResolver) {
  }


  /**
   *
   * afterOk({endLoading, startLoading, formData})
   *
   * @param obj
   */
  openWindow(obj): DhlWindowComponent {
    const {
      submitUrl,
      component,
      data = {},
      width = '800px',
      showCloseBtn = true,
      buttonStyle,
      title = '标题',
      okText = '确定',
      afterOk,
      beforeCheck,
      buttons
    } = obj;
    const popup = document.createElement('window-component');
    const factory = this.componentFactoryResolver.resolveComponentFactory(DhlWindowComponent);
    const popupComponentRef = factory.create(this.injector, [], popup);
    this.applicationRef.attachView(popupComponentRef.hostView);

    popupComponentRef.instance.submitUrl = submitUrl;
    popupComponentRef.instance.data = {...data, showCloseBtn, buttonStyle};
    popupComponentRef.instance.width = width;
    popupComponentRef.instance.title = title;
    popupComponentRef.instance.okText = okText;
    popupComponentRef.instance.buttons = buttons;
    popupComponentRef.instance.afterOk = afterOk;
    popupComponentRef.instance.beforeCheck = beforeCheck;
    popupComponentRef.instance.contentComponent = component;
    popupComponentRef.instance.isVisible = true;
    document.body.appendChild(popup);

    return popupComponentRef.instance;
  }


  openDrawer(obj) {
    const {component, data = {}, width = 800, title = '标题', okText = '确定', submitUrl, afterOk} = obj;
    const drawerService = appInjector().get(NzDrawerService);
    let drawer;

    const close = () => {
      drawer.close();
    };

    drawer = drawerService.create({
      nzTitle: title,
      nzContent: DhlDrawerComponent,
      nzContentParams: {component, okText, submitUrl, afterOk, close, data},
      nzWidth: width,
      nzMaskStyle: {'background-color': 'rgba(0, 0, 0, 0)'}
    });


  }

}




